﻿using System;
using System.Collections.Generic;
using System.Text;
using General.Core;
using General.Core.Extensions;
using General.Core.Infrastructure;
using General.Entities;
using General.Framework;
using General.Framework.Infrastructure;
using General.Framework.Options;
using General.Framework.Security.Admin;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace General.Mvc
{
    /// <summary>
    /// 
    /// </summary>
    public class GeneralEngine : IEngine
    {
        private IConfiguration _configuration;
        private IServiceProvider _serviceProvider { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public GeneralEngine(IConfiguration configuration)
        {
            this._configuration = configuration;
        }

        /// <summary>
        /// 配置对象
        /// </summary>
        public IConfiguration Configuration => _configuration;

        /// <summary>
        /// 服务提供者
        /// </summary>
        public virtual IServiceProvider ServiceProvider => _serviceProvider;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            _serviceProvider = services.BuildServiceProvider();

            return _serviceProvider;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="services"></param>
        public void Initialize(IServiceCollection services)
        {
            services.AddMvc()
               .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver())
               .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //
            services.AddDbContextPool<GeneralDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddAuthentication(o =>
            {
                o.DefaultAuthenticateScheme = CookieAdminAuthInfo.AuthenticationScheme;
                o.DefaultChallengeScheme = CookieAdminAuthInfo.AuthenticationScheme;
            })
                .AddCookie(CookieAdminAuthInfo.AuthenticationScheme, o =>
                {
                    o.Cookie.Domain = "";
                    o.Cookie.HttpOnly = true;
                    o.Cookie.Path = "";
                    o.LoginPath = "/admin/login";
                });

            //程序集依赖注入
            services.AddAssembly("General.Services");

            services.AddScoped<IWorkContext, WorkContext>();
            services.AddScoped<IAdminAuthService, AdminAuthService>();
            services.AddSingleton<IWebHelper, WebHelper>();
            services.AddMemoryCache();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


            services.Configure<CustomOptions>(Configuration.GetSection("Custom"));
        }

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>() where T : class
        {
            return (T)GetServiceProvider().GetRequiredService(typeof(T));
        }

        /// <summary>
        /// 获取ServiceProvider
        /// </summary>
        /// <returns></returns>
        protected IServiceProvider GetServiceProvider()
        {
            var accessor = ServiceProvider.GetService<IHttpContextAccessor>();
            var context = accessor.HttpContext;
            return context != null ? context.RequestServices : ServiceProvider;
        }
    }
}
